<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <nav class="nav-container">
        <div class="nav-left">
          <a href="#" class="nav-item active">主页大厅</a>
          <a href="#" class="nav-item" @click="handleTeacherTeams">教师队伍</a>
        </div>
        <div class="nav-right">
          <button class="user-btn" @click="handleProfileClick">
            <span class="user-icon">👤</span>我的
          </button>
        </div>
      </nav>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 轮播图展示区 -->
      <section class="carousel-section">
        <div class="carousel-container">
          <div class="carousel-wrapper">
            <div
              v-for="(image, index) in activeCarouselImages"
              :key="image.position"
              class="carousel-slide"
              :class="{ active: index === currentSlide }"
            >
              <img :src="image.imageUrl" :alt="image.imageName" />
            </div>
          </div>

          <!-- 轮播指示器 -->
          <div class="carousel-indicators" v-if="activeCarouselImages.length > 1">
            <button
              v-for="(image, index) in activeCarouselImages"
              :key="index"
              class="indicator"
              :class="{ active: index === currentSlide }"
              @click="goToSlide(index)"
            ></button>
          </div>

          <!-- 轮播控制按钮 -->
          <button class="carousel-btn prev" @click="prevSlide" v-if="activeCarouselImages.length > 1">‹</button>
          <button class="carousel-btn next" @click="nextSlide" v-if="activeCarouselImages.length > 1">›</button>
        </div>
      </section>

      <!-- 功能卡片区 -->
      <section class="feature-section">
        <div class="feature-cards">
          <div class="feature-card" @click="handleRecentEvents">
            <div class="card-image">
              <!-- 近期赛事图标 -->
            </div>
            <div class="card-content">
              <h3>近期赛事</h3>
            </div>
          </div>

          <div class="feature-card" @click="handleLatestNews">
            <div class="card-image">
              <!-- 最新通知图标 -->
            </div>
            <div class="card-content">
              <h3>最新通知</h3>
            </div>
          </div>
        </div>
      </section>

      <!-- 最新新闻区 -->
      <section class="intro-section">
        <div class="intro-content">
          <h2 style="border-bottom: 2px solid #e9ecef;padding-bottom: 10px;">最新新闻</h2>

          <!-- 新闻列表 -->
          <div class="news-list" v-if="newsList.length > 0">
            <div
              v-for="news in newsList"
              :key="news.id"
              class="news-item"
              @click="handleNewsClick(news.id)"
            >
              <h2 class="news-title">{{ news.title }}</h2>
              <div class="news-summary" v-if="news.summary">
                <p>{{ news.summary }}</p>
              </div>
            </div>
          </div>

          <!-- 暂无新闻 -->
          <div class="no-news" v-else>
            <p>暂无新闻数据</p>
          </div>
        </div>
        <button class="footer-btn" @click="handleMoreInfo">了解更多相关信息</button>
      </section>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useStudentStore } from '@/stores/student.js'
import { getStudentInfoService } from '@/api/student.js'
import { getCarouselImagesService, getAllNewsService } from '@/api/home.js'

const router = useRouter()
const tokenStore = useTokenStore()
const studentStore = useStudentStore()

// 轮播图数据
const carouselImages = ref([])
const currentSlide = ref(0)
let carouselTimer = null

// 新闻数据
const newsList = ref([])

// 获取学生信息
const studentInfo = computed(() => studentStore.studentInfo)

// 计算属性：获取学生姓名
const studentName = computed(() => {
  return studentStore.getStudentName() || '学生'
})

// 计算属性：获取启用的轮播图
const activeCarouselImages = computed(() => {
  return carouselImages.value.filter(img => img.isActive && img.imageUrl)
})

// 轮播图控制
const goToSlide = (index) => {
  currentSlide.value = index
}

const nextSlide = () => {
  if (activeCarouselImages.value.length > 0) {
    currentSlide.value = (currentSlide.value + 1) % activeCarouselImages.value.length
  }
}

const prevSlide = () => {
  if (activeCarouselImages.value.length > 0) {
    currentSlide.value = currentSlide.value === 0
      ? activeCarouselImages.value.length - 1
      : currentSlide.value - 1
  }
}

// 自动轮播
const startCarousel = () => {
  if (activeCarouselImages.value.length > 1) {
    carouselTimer = setInterval(() => {
      nextSlide()
    }, 5000) // 5秒切换一次
  }
}

const stopCarousel = () => {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
}

// 加载轮播图数据
const loadCarouselImages = async () => {
  try {
    console.log('开始加载轮播图数据...')
    const result = await getCarouselImagesService()
    console.log('轮播图API响应:', result)

    if (result.code === 200 && result.data) {
      carouselImages.value = result.data.sort((a, b) => a.position - b.position)
      console.log('轮播图数据加载成功:', carouselImages.value)
    } else {
      // API调用失败时使用模拟数据
      console.log('轮播图API返回失败，使用默认数据')
      carouselImages.value = getDefaultCarouselImages()
    }

    // 启动自动轮播
    startCarousel()
  } catch (error) {
    console.error('加载轮播图失败:', error)
    // 出错时使用默认数据
    carouselImages.value = getDefaultCarouselImages()
    startCarousel()
  }
}

// 加载新闻数据
const loadNewsList = async () => {
  try {
    console.log('开始加载新闻数据...')
    const result = await getAllNewsService()
    console.log('新闻API响应:', result)

    if (result.code === 200 && result.data && result.data.list) {
      // 只取前3条新闻
      newsList.value = result.data.list.slice(0, 3)
      console.log('新闻数据加载成功:', newsList.value)
    } else {
      // API调用失败时使用模拟数据
      console.log('新闻API返回失败，使用默认数据')
      newsList.value = getDefaultNewsList()
    }
  } catch (error) {
    console.error('加载新闻数据失败:', error)
    // 出错时使用默认数据
    newsList.value = getDefaultNewsList()
  }
}

// 默认轮播图数据
const getDefaultCarouselImages = () => {
  return [
    {
      id: 1,
      position: 1,
      imageName: '校园竞赛平台',
      imageUrl: 'https://via.placeholder.com/1200x400/6278db/ffffff?text=校园智慧竞赛平台',
      isActive: true
    }
  ]
}

// 默认新闻数据
const getDefaultNewsList = () => {
  return [
    {
      id: 1,
      title: '欢迎使用校园智慧竞赛平台',
      summary: '平台为学生和教师提供便捷的竞赛管理和参与服务。'
    }
  ]
}

// 点击新闻项跳转到详情
const handleNewsClick = (newsId) => {
  console.log('跳转到新闻详情:', newsId)
  router.push(`/news-detail/${newsId}`)
}

// 页面挂载时检查登录状态并加载数据
onMounted(async () => {
  // 检查登录状态
  if (!tokenStore.token) {
    router.push('/login')
    return
  }

  // 验证token有效性 - 通过调用API来检查token是否过期
  try {
    console.log('主页：开始验证token有效性，当前token:', tokenStore.token)
    const result = await getStudentInfoService()
    console.log('主页：获取学生信息结果:', result)
    if (result.code === 200) {
      // token有效，更新学生信息
      studentStore.setStudentInfo(result.data)
      console.log('主页：学生信息已更新')
    }
  } catch (error) {
    // API调用失败，可能是token过期，会在request.js的响应拦截器中处理
    console.error('主页：Token验证失败', error)
  }

  // 加载页面数据
  loadCarouselImages()
  loadNewsList()
})

// 页面销毁时清理定时器
onUnmounted(() => {
  stopCarousel()
})

// 处理个人中心点击
const handleProfileClick = () => {
  router.push('/profile')
}

// 处理教师队伍点击
const handleTeacherTeams = () => {
  console.log('跳转到教师队伍页面')
  router.push('/teacher-list')
}

// 近期赛事点击
const handleRecentEvents = () => {
  console.log('跳转到赛事列表页面')
  router.push('/events-list')
}

// 最新通知点击
const handleLatestNews = () => {
  console.log('跳转到通知列表页面')
  router.push('/notifications-list')
}

// 了解更多信息
const handleMoreInfo = () => {
  console.log('跳转到新闻列表页面')
  router.push('/news-list')
}
</script>

<style scoped>
.home-container {
  min-height: 112vh;
  background: #f5f5f5;
}

/* 顶部导航栏 */
.header {
  background: linear-gradient(135deg, #6278db 0%, #635da6 100%);
  padding: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.nav-left {
  display: flex;
  gap: 30px;
}

.nav-item {
  color: rgba(255, 255, 255, 0.8);
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.nav-item:hover,
.nav-item.active {
  color: white;
  background: rgba(255, 255, 255, 0.2);
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.user-icon {
  font-size: 16px;
  opacity: 0.9;
}

/* 主要内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 轮播图展示区 */
.carousel-section {
  margin: 30px 0;
}

.carousel-container {
  position: relative;
  width: 100%;
  height: 500px;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.carousel-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.carousel-slide {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.carousel-slide.active {
  opacity: 1;
}

.carousel-slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 如果图片加载失败，显示渐变背景 */
.carousel-slide::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #6278db 0%, #635da6 100%);
  z-index: -1;
}

/* 轮播指示器 */
.carousel-indicators {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 10px;
}

.indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: none;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: background 0.3s ease;
}

.indicator.active {
  background: white;
}

/* 轮播控制按钮 */
.carousel-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 24px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.carousel-btn:hover {
  background: rgba(0, 0, 0, 0.7);
}

.carousel-btn.prev {
  left: 20px;
}

.carousel-btn.next {
  right: 20px;
}

/* 功能卡片区 */
.feature-section {
  margin: 10px 0;
}

.feature-cards {
  display: flex;
  gap: 20px;
}

.feature-card {
  flex: 1;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  /* box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); */
  cursor: pointer;
  transition: all 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.card-image {
  width: 100%;
  height: 150px;
  position: relative;
  background: linear-gradient(135deg, #6278db 0%, #635da6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

/* 为功能卡片添加图标 */
.card-image::after {
  content: '📋';
  font-size: 36px;
  position: absolute;
  z-index: 1;
}

.feature-card:first-child .card-image::after {
  content: '🏆';
}

.feature-card:last-child .card-image::after {
  content: '📢';
}

.card-content {
  padding: 20px;
  text-align: center;
}

.card-content h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

/* 内容介绍区 */
.intro-section {
  margin: 20px 0;
}

.intro-content {
  background: white;
  border-radius: 15px;
  padding: 40px;
  /* box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); */
  line-height: 1.8;
}

.intro-content h2 {
  color: #333;
  font-size: 24px;
  margin: 0 0 20px 0;
  font-weight: 600;
}

/* 新闻列表样式 */
.news-list {
  margin-top: 20px;
}

.news-item {
  padding: 15px 0;
  margin-bottom: 0;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #e9ecef;
}

.news-item:hover {
  background: rgba(219, 219, 219, 0.05);
}

.news-item:last-child {
  border-bottom: none;
}

.news-title {
  color: #5e5e5e;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.news-summary {
  margin-bottom: 0;
  margin-left: 28px;
}

.news-summary p {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.no-news {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.no-news p {
  margin: 0;
  font-size: 14px;
}

.footer-btn {
  background: linear-gradient(135deg, #6278db 0%, #635da6 100%);
  color: white;
  border: none;
  padding: 15px 40px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 5px 15px rgba(98, 120, 219, 0.3);
  margin-top: 20px;
  margin-left: 200px;
}

.footer-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(98, 120, 219, 0.4);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .nav-container {
    padding: 10px 15px;
  }

  .nav-left {
    gap: 15px;
  }

  .nav-item {
    font-size: 14px;
    padding: 6px 12px;
  }

  .user-btn {
    font-size: 13px;
    padding: 6px 15px;
  }

  .user-icon {
    font-size: 14px;
  }

  .main-content {
    padding: 0 15px;
  }

  .carousel-container {
    height: 400px;
    margin: 20px 0;
  }

  .feature-cards {
    flex-direction: row;
  }

  .intro-content {
    padding: 25px 20px;
  }

  .intro-content h2 {
    font-size: 20px;
  }

  .news-item {
    padding: 12px 0;
  }

  .news-title {
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .nav-left {
    gap: 10px;
  }

  .nav-item {
    font-size: 13px;
    padding: 5px 10px;
  }

  .carousel-container {
    height: 500px;
  }

  .intro-content {
    padding: 20px 15px;
  }

  .footer-btn {
    padding: 12px 30px;
    font-size: 14px;
    margin-left: 0;
    display: block;
    margin: 20px auto 0;
  }

  .news-item {
    padding: 10px 0;
  }

  .news-title {
    font-size: 14px;
  }

  .news-summary p {
    font-size: 13px;
  }
}
</style>
